package com.uenpay.im.ui.old.activity.chat;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.media.Player;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qiyunxin.android.http.view.ResizeLayout;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.GroupMemberManager;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.GroupMemberEntity;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.BusinessCradType;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.MsgStatusType;
import com.qyx.android.message.type.OperationType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.message.type.SendMsgCallBackResult;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.PageData;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.protocol.QyxMsgView;
import com.qyx.android.protocol.SessionModel;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.qyx.android.weight.view.BlockingListView;
import com.qyx.android.weight.view.CircularProgressView;
import com.socks.library.KLog;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.CameraActivity;
import com.uenpay.im.ui.old.activity.OaWebViewActivity;
import com.uenpay.im.ui.old.activity.PushServiceConn;
import com.uenpay.im.ui.old.activity.chat.manage.ChatMsgManage;
import com.uenpay.im.ui.old.activity.chat.manage.ChatRequestCodeManage;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.contacts.ChooseContactsActivity;
import com.uenpay.im.ui.old.activity.crowdfund.CrowdFundActivity;
import com.uenpay.im.ui.old.activity.funds.FundsHandle;
import com.uenpay.im.ui.old.activity.funds.FundsManageActivity;
import com.uenpay.im.ui.old.activity.funds.GetFundsChatAmountInvokeItem;
import com.uenpay.im.ui.old.activity.group.GroupDetailActivity;
import com.uenpay.im.ui.old.activity.group.GroupMemberActivity;
import com.uenpay.im.ui.old.activity.map.LocationReportActivity;
import com.uenpay.im.ui.old.activity.publicnumber.PublicNumHandle;
import com.uenpay.im.ui.old.activity.publicnumber.PublicNumMenu;
import com.uenpay.im.ui.old.activity.publicnumber.PublicNumberDetailActivity;
import com.uenpay.im.ui.old.activity.red.SendRedToGroupActivity;
import com.uenpay.im.ui.old.activity.red.SendRedToPersonalActivity;
import com.uenpay.im.ui.old.activity.transfer.TransferActivity;
import com.uenpay.im.adapter.ChatAdapter;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.ShareData;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.entities.SendFile;
import com.uenpay.im.entities.chatbean.AttachModel;
import com.uenpay.im.entities.chatbean.MsgAudioModel;
import com.uenpay.im.entities.chatbean.MsgCradModel;
import com.uenpay.im.entities.chatbean.MsgCrowdFundsModel;
import com.uenpay.im.entities.chatbean.MsgFileModel;
import com.uenpay.im.entities.chatbean.MsgGifModel;
import com.uenpay.im.entities.chatbean.MsgImageModel;
import com.uenpay.im.entities.chatbean.MsgLocationModel;
import com.uenpay.im.entities.chatbean.MsgRedModel;
import com.uenpay.im.entities.chatbean.MsgRequestVideoChatModel;
import com.uenpay.im.entities.chatbean.MsgTextModel;
import com.uenpay.im.entities.chatbean.MsgVideoModel;
import com.uenpay.im.panel.FacePanelManager;
import com.uenpay.im.panel.PanelManagerInterface;
import com.uenpay.im.panel.PanelMoreManager;
import com.uenpay.im.panel.emojitype.CheckEmojiEntity;
import com.uenpay.im.panel.gif.ViewGifCover;
import com.uenpay.im.panel.more.IMoreOnClickListener;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.smallvideo.MediaRecorderActivity;
import com.uenpay.smallvideo.model.MediaRecorderConfig;
import com.qyx.videochat.util.VideoChatResultType;
import com.uenpay.util.app.base.BaseActivity;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.UUID;

/**
 * 会话页面
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
@SuppressLint("DefaultLocale")
public class ChatActivity extends BaseActivity {

    private LinearLayout forward_success_layout;
    private RelativeLayout group_funds_layout;
    private TextView group_funds_amount;
    private PublicNumHandle mPublicNumHandle = new PublicNumHandle();
    private ResizeLayout mResizeLayout;
    private InputMethodManager inputManager;
    /**
     * 群组成员表
     */
    private GroupMemberManager mGroupMemberManager = new GroupMemberManager();
    /**
     * 消息发送方名称(登录者用户名)
     */
    private String from_cust_name = "";
    private ArrayList<ImageSize> size = new ArrayList<ImageSize>();
    /**
     * 未读消息数量
     */
    private TextView unread_msg_count_tv;
    /**
     * 未读消息
     */
    private RelativeLayout unread_msg_layout;
    /**
     * 会话Model
     */
    private SessionModel sessionModel = null;
    /**
     * 接受者姓名(个人、群)
     */
    private String to_name;
    private int has_count = 0;
    /**
     * 是否为管理员类型(0：false;1：true;default：-1)
     */
    private int is_group_admin = 0;
    /**
     * 刷新的listview 聊天列表
     */
    private BlockingListView listView;
    /**
     * 内容编辑框
     */
    private EditText sendEdit;
    /**
     * 群聊中有新成员加入，审核成员按钮(PS:admin)
     */
    private RelativeLayout hasNewFriendButton;
    /**
     * listview 分页加载数据，每页数据大小（PS:10）
     */
    protected int pageSize = 10;
    /**
     * 分页加载数据的每页数据(setList,getList,list)(PS:list中为消息对象的view：QyxTopMsgView，消息对象为：
     * QyxTopMsg)
     */
    private PageData mPageData = null;
    /**
     * 群聊信息数据库管理类实例
     */
    private GroupTalkDbManager groupTalkDbManager = new GroupTalkDbManager();
    /**
     * 消息广播接收器(处理：接收消息，更给发送状态，群聊'@'某人，清除聊天记录)
     */
    private MsgReceiver msgReceiver;
    /**
     * 聊天信息适配器
     */
    private ChatAdapter chatAdapter;
    /**
     * 聊天信息数据库操作类实例
     */
    private TalkMsgManager msgManager = new TalkMsgManager();
    /**
     * 消息界面数据库操作类实例
     */
    private TopListMsgManager topListMsgManager = new TopListMsgManager();
    /**
     * 填充 聊天信息适配器的ArrayList集合
     */
    private ArrayList<QyxMsgView> qyxMsgsArrayList = new ArrayList<QyxMsgView>();
    /**
     * 转发消息对象
     */
    private BaseContentModel forwardMessage;
    /**
     * 文件工具类实例
     */
    private FileUtils fileUtils = new FileUtils(IMApplication.appName);
    /**
     * titleTextView:聊天名称,rightTextView:设置(活动)
     */
    private TextView titleTextView, rightTextView;

    /**
     * listview滚动时，判断是否在加载数据标识
     */
    private boolean is_get_history = false;
    /**
     * 查看聊天页面的历史消息时，有新消息时，显示消息数量的控件
     */
    private TextView unread_msg;
    private FacePanelManager.IRecordListener recordListener;
    private RelativeLayout layoutLoading;
    private TextView textTimeLeft;
    private TextView textMessage;
    private RotateAnimation rotate;
    private ImageView ivCircle;

    /**
     * 发送handler message 对象
     */
    private class SendStatusCls {
        private String msg_no;
        private int status_code;
    }

    /**
     * listview滚动时标识是否在刷新.default:true
     */
    private boolean is_freshing = true;
    /**
     * listview能否刷新标识.default:true
     */
    private boolean freshable = true;
    private boolean isScrollTop = false;

    /**
     * listview下拉时出现的进度条控件
     */
    private CircularProgressView loading;
    private ArrayList<PhotoItem> select_gl_arr = new ArrayList<PhotoItem>();// 选中发送的图片
    /**
     * 是否显示群成员昵称
     */
    private int is_show_group_member_name = 0;
    private View recordView;
    private FacePanelManager facePanelManager = null;
    private PanelManagerInterface.IHideFacePanel hideFacePanel;

    private void finishActivity() {
        /** 隐藏软键盘 **/
        if (hideFacePanel != null) {
            hideFacePanel.hideFacePanel();
        }
        inputManager.hideSoftInputFromWindow(sendEdit.getWindowToken(), 0);
        Player.getInstance().Stop();
        finish();
    }

    /**
     * 控制下拉时ProgressBar是否显示的方法
     *
     * @param bl
     */
    private void is_show_pb(boolean bl) {
        is_freshing = bl;
        if (!bl) {
            loading.setVisibility(View.GONE);
        } else {
            loading.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化View
     *
     * @return
     */
    public void initView() {
        /************************************************************
         *                      动画及其布局
         * **********************************************************
         */
        rotate = new RotateAnimation(0, -360,
                Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(5000);
        rotate.setRepeatCount(Animation.INFINITE);
        layoutLoading = (RelativeLayout) findViewById(R.id.rl_loading_layout);
        ivCircle = (ImageView) findViewById(R.id.iv_circle);
        textTimeLeft = (TextView) findViewById(R.id.tv_time);
        textMessage = (TextView) findViewById(R.id.tv_message);
        /**
         * *********************************************************** over
         */

        group_funds_layout = (RelativeLayout) findViewById(R.id.group_funds_layout);
        group_funds_amount = (TextView) findViewById(R.id.group_funds_tv);
        forward_success_layout = (LinearLayout) findViewById(R.id.forward_success_layout);
        mResizeLayout = (ResizeLayout) findViewById(R.id.messagelist);
        recordView = findViewById(R.id.recordView);
        unread_msg = (TextView) findViewById(R.id.unread_msg_bottom_tv);
        unread_msg_count_tv = (TextView) findViewById(R.id.unread_msg_top_count_tv);
        unread_msg_layout = (RelativeLayout) findViewById(R.id.unread_msg_top_layout);
        hasNewFriendButton = (RelativeLayout) findViewById(R.id.has_new_friend);
        titleTextView = (TextView) findViewById(R.id.title_textview);
        rightTextView = (TextView) findViewById(R.id.title_right_tv);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        rightTextView.setText(getResources().getString(R.string.setting));
        listView = (BlockingListView) findViewById(R.id.listView);
        sendEdit = (EditText) findViewById(R.id.editText);
        View headerLayout = View.inflate(this, R.layout.activity_loading_progressbar, null);
        loading = (CircularProgressView) headerLayout.findViewById(R.id.loading);
        listView.addHeaderView(headerLayout);
    }

    /**
     * 初始化Event
     *
     * @return
     */
    public void initListener() {
        group_funds_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(ChatActivity.this, FundsManageActivity.class);
                intent.putExtra("chat_id", sessionModel.getSessionId() + "");
                intent.putExtra("selected_type", 1);
                startActivity(intent);
            }
        });
        findViewById(R.id.close_iv).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                group_funds_layout.setVisibility(View.INVISIBLE);
            }
        });
        /** 新成员审核 **/
        hasNewFriendButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                groupTalkDbManager.updateGroupNewMemberCount(sessionModel.getSessionId(), 0);
                Bundle bundle = new Bundle();
                bundle.putLong("group_id", sessionModel.getSessionId());
                ActivityHandle.startActivity(ChatActivity.this, TalkApplyFriendsListActivity.class, bundle, -1);

                hasNewFriendButton.setVisibility(View.GONE);
            }
        });
        unread_msg_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                /** 获取指定的未读消息数量 **/
                getDBmsgAndRefresh();
                pageSize = 10;
                listView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        listView.setSelection(0);
                    }
                }, 500);
                chatAdapter.addUnreadMsgLineToTop();
                unread_msg_layout.setVisibility(View.GONE);
            }
        });
        findViewById(R.id.title_right_layout).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Utils.hideSoftKeyboard(sendEdit);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (sessionModel.getOperationType() == OperationType.PUBLIC_NUM && sessionModel.getSessionType() == PacketType.PERSONAL) {
                    Intent intent = new Intent(ChatActivity.this, PublicNumberDetailActivity.class);
                    intent.putExtra("cust_id", sessionModel.getSessionId() + "");
                    startActivity(intent);
                } else {
                    Bundle bu = new Bundle();
                    bu.putString("to_id", sessionModel.getSessionId() + "");
                    bu.putString("chatType", sessionModel.getSessionType() + "");
                    if (sessionModel.getSessionType() == PacketType.PERSONAL) {
                        bu.putString("name", to_name);
                        Utils.startActivityForResult(ChatActivity.this, TalkPersonalDetailActivity.class, bu,
                                ChatRequestCodeManage.TALK_SETTING);
                    } else {
                        Utils.startActivityForResult(ChatActivity.this, GroupDetailActivity.class, bu, ChatRequestCodeManage.TALK_SETTING);
                    }
                }
            }
        });

        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finishActivity();
            }
        });

        /** 监听消息列表滚动事件,控制底部新消息的显示和隐藏 **/
        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (listView.getLastVisiblePosition() < listView.getCount() - 1) {
                    is_get_history = true;
                }
                if (unread_msg != null) {
                    if (listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
                        is_get_history = false;
                        if (unread_msg.getVisibility() == View.VISIBLE) {
                            unread_msg.setVisibility(View.GONE);
                            unread_msg.setText("");
                        }
                    }
                }

                if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                    if (isScrollTop) {
                        if (is_freshing || !freshable) {
                            return;
                        }
                        is_show_pb(true);
                        if (unread_msg_layout.getVisibility() == View.VISIBLE) {
                            unread_msg_layout.setVisibility(View.GONE);
                        }
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                pageSize = 10;
                                getDBmsgAndRefresh();
                            }
                        }, 500);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (!TextUtils.isEmpty(unread_msg.getText().toString())) {
                    if (unread_msg.getTag() != null) {
                        int count = (Integer) unread_msg.getTag();
                        if (listView.getLastVisiblePosition() == listView.getCount() - count) {
                            count--;
                            unread_msg.setTag(count);
                            if (count > 99) {
                                unread_msg.setText("99");
                            } else if (count < 1) {
                                unread_msg.setVisibility(View.GONE);
                                unread_msg.setText("");
                            } else {
                                unread_msg.setText(count + "");
                            }
                        }
                    }
                }

                if (firstVisibleItem == 0) {
                    isScrollTop = true;
                } else {
                    isScrollTop = false;
                }
            }
        });

        listView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                inputManager.hideSoftInputFromWindow(sendEdit.getWindowToken(), 0);
                if (hideFacePanel != null) {
                    hideFacePanel.hideFacePanel();
                }
                return false;
            }

        });

        /** 点击底部未读消息,消息列表滚动到底部 **/
        unread_msg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                scrollToEnd();
            }
        });
        recordListener = new FacePanelManager.IRecordListener() {
            @Override
            public void onStart() {
                KLog.e("==========开始录音");
                layoutLoading.setVisibility(View.VISIBLE);
                ivCircle.setAnimation(rotate);
            }

            @Override
            public void onFailed() {
                KLog.e("==========录音失败");
                layoutLoading.setVisibility(View.GONE);
            }

            @Override
            public void onRecording(long time ) {
                KLog.e("==========录音剩余时间"+(60-time));
                textTimeLeft.setText(""+(60-time));
            }

            @Override
            public void onFinished() {
                KLog.e("==========录音结束");
                layoutLoading.setVisibility(View.GONE);
            }

            @Override
            public void onMoving(boolean inSide) {
                KLog.e("==========onMoving isInside"+inSide);
                if (inSide) {
                    textMessage.setText("向上滑动取消录音");
                } else {
                    textMessage.setText("松开取消录音");
                }
            }
        };
    }

    /**
     * 初始化数据
     **/
    private void initData() {
        is_freshing = true;
        freshable = true;
        is_group_admin = 0;
        sessionModel = null;
        is_get_history = false;
        isScrollTop = false;
        rightTextView.setText(getResources().getString(R.string.setting));
        qyxMsgsArrayList.clear();
        if (unread_msg != null) {
            unread_msg.setText("");
            unread_msg.setVisibility(View.GONE);
        }

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        sessionModel = bundle.getParcelable("session");
        initFacePanelView();
        if (sessionModel.getOperationType() == OperationType.PUBLIC_NUM) {
            /** 用户类型是OperationType.PUBLIC_NUM获取公众号数据 **/
            getMenu(sessionModel.getSessionId());
        } else if (sessionModel.getOperationType() == OperationType.FUNDS_GROUP) {
            /** 重新初始化面板 **/
            /** 隐藏菜单 **/
            if (facePanelManager != null)
                facePanelManager.hidePublicNumView();
            getGroupFundsAmount();
        } else {
            /** 隐藏菜单 **/
            if (facePanelManager != null)
                facePanelManager.hidePublicNumView();
        }
        if (!TextUtils.isEmpty(bundle.getString("stranger_name"))) {
            to_name = bundle.getString("stranger_name");
        }
        getChatInfo();

        titleTextView.setText(to_name);
        /** 判断是否转发到该会话 **/
        if (bundle.getParcelable("forwardMsg") != null) {
            forwardMessage = bundle.getParcelable("forwardMsg");
            initMoreAdapter();
            showForwardDialog();
        }
        chatAdapter = new ChatAdapter(ChatActivity.this, qyxMsgsArrayList, sendEdit, is_show_group_member_name);
        listView.setAdapter(chatAdapter);
        getDBmsgAndRefresh();

        if (bundle.getInt("unread_msg_count") != 0) {
            int count = bundle.getInt("unread_msg_count");
            if (count > 10) {
                // 该会话未读消息数量
                unread_msg_layout.setVisibility(View.VISIBLE);
                unread_msg_count_tv.setText(MessageFormat.format(getResources().getString(R.string.unread_msg), count));
                pageSize = count - 10;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // initFacePanelView();
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_message_list;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        initData();
    }

    /**
     * 初始化表情面板
     */
    private void initFacePanelView() {
        View view = findViewById(R.id.face_panel);
        facePanelManager = new FacePanelManager(this, view, recordView, mResizeLayout,
                sessionModel.getOperationType() == OperationType.PUBLIC_NUM ? true : false);
        facePanelManager.initListener();
        initMoreAdapter();
        facePanelManager.onSendAudioListener(new PanelManagerInterface.ISendAudioListener() {

            @Override
            public void onSendAudio(int audioTime, String audioPath) {
                sendRecordAudio(audioTime, audioPath);
            }
        });

        facePanelManager.onSendGifListener(new PanelManagerInterface.ISendGifListener() {

            @Override
            public void onSendGif(ViewGifCover mGif, String gifName) {
                if (!TextUtils.isEmpty(gifName)) {
                    // 自定义表情
                    MsgGifModel msgGifModel = new MsgGifModel();
                    msgGifModel.setGifName(gifName);
                    sendMsgByContentModel(msgGifModel);
                } else {
                    MsgGifModel msgGifModel = new MsgGifModel();
                    msgGifModel.setFileHash(mGif.fileHash);
                    msgGifModel.setFileId(mGif.fileId);
                    sendMsgByContentModel(msgGifModel);
                }

            }
        });
        facePanelManager.onSendTextListener(new PanelManagerInterface.ISendTextListener() {

            @Override
            public void onSendTextContent(String editContent) {
                MsgTextModel contentModel = new MsgTextModel();
                contentModel.setContent(editContent);
                sendMsgByContentModel(contentModel);
            }
        });

        facePanelManager.onInputSpecialChar(new PanelManagerInterface.IInputSpecialChar() {

            @Override
            public void onInputSpecialChar() {
                // 目前只监听了@
                /** 如果是群聊 **/
                if (sessionModel.getSessionType() == PacketType.GROUP) {
                    /** 如果是输入的@（显示群里面的群员） **/
                    inputManager.hideSoftInputFromWindow(sendEdit.getWindowToken(), 0);
                    /** 选择群成员列表 **/
                    Bundle bundle = new Bundle();
                    bundle.putString("group_id", sessionModel.getSessionId() + "");
                    bundle.putInt("type", 2);
                    ActivityHandle.startActivity(ChatActivity.this, GroupMemberActivity.class, bundle, ChatRequestCodeManage.CHECK_MEMBER);
                }
            }
        });

        facePanelManager.onPublicNumOnclick(new PanelManagerInterface.IPublicNumOnClick() {

            @Override
            public void onPublicNumClick(String url) {
                if (!TextUtils.isEmpty(url)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    ActivityHandle.startActivity(ChatActivity.this, OaWebViewActivity.class, bundle, -1);
                }
            }
        });

        facePanelManager.onSendHideFacePanel(new PanelManagerInterface.ISendHideFacePanel() {

            @Override
            public void onHideFacePanel(PanelManagerInterface.IHideFacePanel mHideFacePanel) {
                hideFacePanel = mHideFacePanel;
            }
        });

        facePanelManager.onScorllToEnd(new PanelManagerInterface.IScrollToEnd() {

            @Override
            public void onScrollToEnd() {
                scrollToEnd();
            }
        });

        facePanelManager.addOnRecordListener(recordListener);

    }

    /**
     * 更多数据
     */
    private void initMoreAdapter() {
        if (facePanelManager == null)
            return;
        facePanelManager.initMoreAdapter(PanelMoreManager.getPanelMoreData(sessionModel.getSessionType()), new IMoreOnClickListener() {

            @Override
            public void onMoreClick(int type) {
                if (type == 1) {
                    size.clear();
                    Intent getImageByCamera = new Intent(ChatActivity.this, CameraActivity.class);
                    size.add(new ImageSize(240, 240, ".small"));
                    size.add(new ImageSize(720, 720, ""));
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("size", size);
                    getImageByCamera.putExtras(bundle);
                    startActivityForResult(getImageByCamera, ChatRequestCodeManage.CHOOSE_TAKE_PHOTO_REQUEST_CODE);
                } else if (type == 2) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("max_select_count", 9);
                    ActivityHandle.startActivity(ChatActivity.this, PhotoActivity.class, bundle,
                            ChatRequestCodeManage.CHOOSE_IMAGE_REQUEST_CODE);
                } else if (type == 3) {
                    ActivityHandle.startActivity(ChatActivity.this, LocationReportActivity.class, null,
                            ChatRequestCodeManage.CHOOSE_LOCATION_CODE);
                } else if (type == 4) {
                    ActivityHandle.startActivity(ChatActivity.this, ChooseSendFileActivity.class, null,
                            ChatRequestCodeManage.FILE_SELECT_CODE);
                } else if (type == 5) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isChooseCrad", true);
                    ActivityHandle.startActivity(ChatActivity.this, ChooseContactsActivity.class, bundle,
                            ChatRequestCodeManage.CRAD_SELECT_CODE);
                } else if (type == 6) {
                    Bundle bundle = new Bundle();
                    bundle.putString("chat_id", sessionModel.getSessionId() + "");
                    bundle.putString("chat_name", to_name);
                    if (sessionModel.getSessionType() == PacketType.PERSONAL) {
                        ActivityHandle.startActivity(ChatActivity.this, SendRedToPersonalActivity.class, bundle,
                                ChatRequestCodeManage.RED_SELECT_CODE);
                    } else {
                        ActivityHandle.startActivity(ChatActivity.this, SendRedToGroupActivity.class, bundle,
                                ChatRequestCodeManage.RED_SELECT_CODE);
                    }
                } else if (type == 7) {
                    sendVideoChat();
                } else if (type == 8) {
                    // 江湖救急
                    Intent intent = new Intent(ChatActivity.this, CrowdFundActivity.class);
                    intent.putExtra("chatid", sessionModel.getSessionId() + "");
                    startActivityForResult(intent, ChatRequestCodeManage.CROWD_FUND);
                } else if (type == 9) {
                    Intent intent = new Intent(ChatActivity.this, TransferActivity.class);
                    intent.putExtra("cust_id", sessionModel.getSessionId() + "");
                    startActivity(intent);
                } else if (type == 10) {
                    sendVideo();
                }
            }
        });
    }

    /**
     * 发送视频
     */
    private void sendVideo() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler().doH264Compress(true).smallVideoWidth(width)
                // .smallVideoWidth(dm.widthPixels)
                .smallVideoHeight(height / 3).recordTimeMax(6 * 1000).maxFrameRate(30).captureThumbnailsTime(1)
                .recordTimeMin((int) (1.5 * 1000)).build();

        Intent intent = new Intent(ChatActivity.this, MediaRecorderActivity.class);
        intent.putExtra("media_recorder_config_key", config);
        startActivityForResult(intent, ChatRequestCodeManage.SEND_VIDEO);
        // MediaRecorderActivity.goSmallVideoRecorder(ChatActivity.this,
        // PreviewVideoActivity.class.getName(), config);
    }

    /**
     * 获取群经费
     */
    private void getGroupFundsAmount() {
        FundsHandle.getChatFundsAmount(sessionModel.getSessionId() + "", new FundsHandle.IGetChatFundsAmount() {

            @Override
            public void onGetFundsAmount(GetFundsChatAmountInvokeItem.GetFundsChatAmountInvokeItemResult result) {
                if (result != null && result.status == HttpInvokeResultCode.RESULT_OK) {
                    group_funds_layout.setVisibility(View.VISIBLE);
                    group_funds_amount.setText(MessageFormat.format(getResources().getString(R.string.red_size), result.leftAmount));
                }
            }
        });
    }

    ;

    @Override
    protected void onPause() {
        /** 暂停语音播放 **/
        if (chatAdapter != null) {
            chatAdapter.stopPlayRecord();
        }
        /** 将与该好友的消息数量改为已读 **/
        topListMsgManager.clearMsgUnreadCount(sessionModel.getSessionId(), sessionModel.getSessionType());
        /** 标记现在正在显示的页面是会话页面 **/
        ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_NULL);
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sessionModel.getSessionType() == PacketType.GROUP) {
            getChatInfo();
            titleTextView.setText(to_name + "(" + has_count + ")");
        }

        ShareData.getInstance().setChatId(sessionModel.getSessionId() + "");
        /** 注册广播 **/
        if (msgReceiver == null) {
            IntentFilter intentFilter = new IntentFilter();
            /** 接受消息广播 **/
            intentFilter.addAction(BroadcastAction.ACTION_MSG_RECIVE);
            /** 清空消息广播 **/
            intentFilter.addAction(BroadcastAction.CLEAR_MSG_ACTION);
            /** 修改文件下载状态广播 **/
            intentFilter.addAction(BroadcastAction.UPDATE_DOWNLAOD_FILE_STAUS);
            /** 发送消息状态广播 **/
            intentFilter.addAction(BroadcastAction.ACTION_MSG_SEND_STAUTS);
            /** 对方拒绝视频通话 **/
            intentFilter.addAction(BroadcastAction.ACTION_REFUSE_VIDEO_CHAT);
            /** 对方撤销某条消息 **/
            intentFilter.addAction(BroadcastAction.ACTION_WITHDRAW_MSG);
            /** @ 某人广播 **/
            intentFilter.addAction(BroadcastAction.ACTION_MESSAGE_AT);
            /** 删除好友 **/
            intentFilter.addAction(BroadcastAction.DELETE_FRIEND_ACTION);
            /** 取消呼叫视频通话 **/
            intentFilter.addAction(BroadcastAction.ACTION_CANCEL_CALL_VIDEO_CHAT);
            /** 刷新表情 **/
            intentFilter.addAction(BroadcastAction.ACTION_REFRESH_STICKER);
            msgReceiver = new MsgReceiver();
            registerReceiver(msgReceiver, intentFilter);
        }
        PushServiceConn.getInstance(ChatActivity.this).startChatService();
        ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_TALK_DETAIL);
    }

    private void getDBmsgAndRefresh() {
        int offset = chatAdapter.getCount() - chatAdapter.time_msg_count - chatAdapter.unread_msg_line;
        final int firstVisPos = listView.getFirstVisiblePosition();
        View firstVisView;
        if (offset == 0) {
            firstVisView = listView.getChildAt(0);
        } else {
            firstVisView = listView.getChildAt(1);
        }
        final int top = firstVisView != null ? firstVisView.getTop() : 0;

        // Block children layout for now
        listView.setBlockLayoutChildren(true);

        if (sessionModel.getSessionType() == PacketType.GROUP) {
            /** 获取群聊聊天记录 **/
            mPageData = msgManager.queryMsg(pageSize, offset, 0, 0, sessionModel.getSessionId());
        } else if (sessionModel.getSessionType() == PacketType.PERSONAL) {
            /** 获取单聊聊天记录 **/
            mPageData = msgManager.queryMsg(pageSize, offset, Long.valueOf(IMApplication.getCustId()), sessionModel.getSessionId(), 0);
        }
        /** 时间消息数量 **/
        chatAdapter.time_msg_count += mPageData.time_msg_count;

        /** 设置adpter更新listView **/
        if (mPageData != null) {
            qyxMsgsArrayList = mPageData.getList();
        }
        // Number of items added before the first visible item
        final int itemsAddedBeforeFirstVisible = qyxMsgsArrayList.size();
        if (itemsAddedBeforeFirstVisible < pageSize) {
            freshable = false;
        }
        chatAdapter.prependMessage(qyxMsgsArrayList);

        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.setSelection(firstVisPos + itemsAddedBeforeFirstVisible + 1);
                // listView.setSelectionFromTop(firstVisPos
                // + itemsAddedBeforeFirstVisible + 1, top);
                listView.setBlockLayoutChildren(false);
                is_freshing = false;
                is_show_pb(false);
            }
        });
    }

    /**
     * 转发对话框
     */
    private void showForwardDialog() {

        DialogUtility.showDialog(ChatActivity.this, R.string.confirm_to_send_in_this_group, R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        sendMsgByContentModel(forwardMessage);
                    }
                });
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == ChatRequestCodeManage.CHOOSE_IMAGE_REQUEST_CODE) {
                /** 相册 **/
                select_gl_arr = (ArrayList<PhotoItem>) data.getSerializableExtra("gl_arr");
                if (select_gl_arr.size() > 0) {
                    for (int i = 0; i < select_gl_arr.size(); i++) {
                        String path = select_gl_arr.get(i).getPath();
                        new SendImageAsyncTask(path, new SendImageAsyncTask.ISendImageATListener() {
                            @Override
                            public void onResult(MsgImageModel imageModel) {
                                sendMsgByContentModel(imageModel);
                            }
                        }).execute();
                    }
                }

            } else if (requestCode == ChatRequestCodeManage.CHOOSE_TAKE_PHOTO_REQUEST_CODE) {
                /** 拍照 **/
                String big_pic_filename = data.getStringExtra("big_pic_filename");
                new SendImageAsyncTask(big_pic_filename, new SendImageAsyncTask.ISendImageATListener() {
                    @Override
                    public void onResult(MsgImageModel imageModel) {
                        sendMsgByContentModel(imageModel);
                    }
                }).execute();
            } else if (requestCode == ChatRequestCodeManage.CHOOSE_LOCATION_CODE) {
                /** 发送地理位置 **/
                Bundle bu = data.getExtras();
                double locationlng = bu.getDouble("locationlng");
                double locationlat = bu.getDouble("locationlat");
                String address = bu.getString("addr");

                MsgLocationModel locationModel = new MsgLocationModel();
                locationModel.setLatitude(locationlat + "");
                locationModel.setLongitude(locationlng + "");
                locationModel.setContent(address);
                sendMsgByContentModel(locationModel);
            } else if (requestCode == ChatRequestCodeManage.FILE_SELECT_CODE) {
                /** 发送文件 **/
                SendFile mSendFile = data.getParcelableExtra("send_file");
                if (mSendFile == null) {
                    return;
                }
                File file = new File(mSendFile.filePath);
                byte[] bytes = null;
                try {
                    bytes = Utils.getBytesFromFile(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                MsgFileModel msgFileModel = new MsgFileModel();
                msgFileModel.setName(mSendFile.fileName);
                msgFileModel.setSize(bytes.length + "");
                AttachModel attachmentModel = new AttachModel();
                attachmentModel.setFileLocalPath(mSendFile.filePath);
                msgFileModel.setAttachmentModel(attachmentModel);
                sendMsgByContentModel(msgFileModel);
            } else if (requestCode == ChatRequestCodeManage.CRAD_SELECT_CODE) {
                FriendEntity friendEntity = (FriendEntity) data.getSerializableExtra("selectedUser");
                if (friendEntity != null)
                    showSendCradDailog(friendEntity);
            } else if (requestCode == ChatRequestCodeManage.RED_SELECT_CODE) {
                String content = data.getStringExtra("content");
                String packetsid = data.getStringExtra("packetsid");
                MsgRedModel msgRedModel = new MsgRedModel();
                msgRedModel.setPacketsid(packetsid);
                msgRedModel.setContent(content);
                sendMsgByContentModel(msgRedModel);
            } else if (requestCode == ChatRequestCodeManage.CHECK_MEMBER) {
                /** 输入框显示要@的用户名称 **/
                String name = data.getStringExtra("cust_name");
                String result = sendEdit.getText().toString() + name + " ";
                sendEdit.setText(result);
                sendEdit.setSelection(result.length());
                sendEdit.setFocusable(true);
            } else if (requestCode == ChatRequestCodeManage.FORWARD_MSG) {
                forward_success_layout.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        forward_success_layout.setVisibility(View.GONE);
                    }
                }, 1000);
                /** 转发成功,重新获取数据 **/
                initData();
            } else if (requestCode == ChatRequestCodeManage.CROWD_FUND) {
                /** 众筹(江湖救急) **/
                String content = data.getStringExtra("memo");
                String amount = data.getStringExtra("amount");
                String id = data.getStringExtra("fundid");
                MsgCrowdFundsModel crowdFundsModel = new MsgCrowdFundsModel();
                crowdFundsModel.setAmount(amount);
                crowdFundsModel.setFundId(id);
                crowdFundsModel.setContent(content);
                sendMsgByContentModel(crowdFundsModel);
            } else if (requestCode == ChatRequestCodeManage.SEND_VIDEO) {
                // 视频地址
                String path = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                KLog.d("vidoe path=" + path);
                // 视频封面地址
                String screenshot_path = data.getStringExtra(MediaRecorderActivity.VIDEO_SCREENSHOT);
                Bitmap compressBitmap = ImageUtil.CompressImageSameRadioScale(screenshot_path, 100, 960, 960);
                MsgVideoModel msgVideoModel = new MsgVideoModel();
                msgVideoModel.setScreeHostH(compressBitmap.getHeight());
                msgVideoModel.setScreeHostW(compressBitmap.getWidth());
                msgVideoModel.setScreeHostLocalPath(screenshot_path);
                AttachModel attachModel = new AttachModel();
                attachModel.setFileLocalPath(path);
                msgVideoModel.setAttachmentModel(attachModel);
                sendMsgByContentModel(msgVideoModel);
                if (compressBitmap != null && !compressBitmap.isRecycled()) {
                    compressBitmap.recycle();
                }
            }
        }

        if (requestCode == ChatRequestCodeManage.TALK_SETTING) {
            if (resultCode == ChatRequestCodeManage.QUIT_GROUP_TALK) {
                /** 退出群 **/
                finish();
            } else if (resultCode == ChatRequestCodeManage.UPDATE_SHOW_GROUP_MEMBER_NAME) {
                /** 显示群成员昵称 **/
                GroupTalkEntity groupTalk = groupTalkDbManager.queryGroupByGroupId(sessionModel.getSessionId());
                if (groupTalk != null) {
                    is_show_group_member_name = groupTalk.is_show_member_name;
                }

                GroupMemberEntity mGroupMemberEntity = mGroupMemberManager.getSingleParticipant(sessionModel.getSessionId() + "",
                        IMApplication.getCustId());
                if (mGroupMemberEntity != null) {
                    if (!TextUtils.isEmpty(mGroupMemberEntity.nick_name)) {
                        from_cust_name = mGroupMemberEntity.nick_name;
                    } else {
                        from_cust_name = IMApplication.config.getUserName();
                    }
                }
                chatAdapter.setIsShowMemberName(is_show_group_member_name);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendMsgByContentModel(BaseContentModel baseContentModel) {
        baseContentModel.setToCustName(to_name);
        baseContentModel.setFromCustName(from_cust_name);
        SendMsgHandle.sendMsg(baseContentModel, sessionModel, new SendMsgHandle.ISendMsgCallBack() {

            @Override
            public void onSendMsgResult(int sendMsgResult, QyxMsg qyxMsg) {
                QyxMsgView message = new QyxMsgView();
                message.msg = qyxMsg;
                chatAdapter.addMessage(message);
                scrollToEnd();
                if (sendMsgResult == SendMsgCallBackResult.FAILED_NOT_FRIEND && qyxMsg.send_status.equals("n")) {
                    addVerifMsg(qyxMsg);
                    return;
                }

                if (qyxMsg.msg_content_type == MsgContentType.REQUEST_VIDEO_CHAT) {
                    ChatMsgManage mChatMsgManage = new ChatMsgManage(ChatActivity.this);
                    mChatMsgManage.connectToRoom1(qyxMsg, false, 0);
                }
            }
        }, new SendMsgHandle.IUploadAttachFaild() {

            @Override
            public void onUploadFailed(String msg_no) {
                if (!TextUtils.isEmpty(msg_no) && chatAdapter != null) {
                    chatAdapter.updateMsgFailed(msg_no);
                }
            }
        });

    }

    /**
     * 转发
     *
     * @param message
     */
    public void startForwardMessagePickFriend(QyxMsg message) {
        Bundle bundle = new Bundle();
        bundle.putParcelable("forwardMsg", message.baseContentModel);
        Utils.startActivityForResult(ChatActivity.this, PickTalkActivity.class, bundle, ChatRequestCodeManage.FORWARD_MSG);

    }

    /**
     * 发送语音方法
     **/
    private void sendRecordAudio(int timeTrad, String recoderPath) {
        /** 保存录音在本地数据库中 **/
        // File file = new File(recoderPath);
        // byte[] bytes = null;
        // try {
        // bytes = Utils.getBytesFromFile(file);
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        File file2 = fileUtils.getFileByTime("amr");
        Utils.copyFile(recoderPath, file2.getAbsolutePath());
        // QyxMsg qyxMsg = new QyxMsg();
        // qyxMsg.category = MsgContentType.AUDIO;
        // qyxMsg.file_path = file2.getAbsolutePath();
        // if (timeTrad > 60) {
        // timeTrad = 60;
        // }
        // qyxMsg.durationTime = timeTrad;

        MsgAudioModel audioModel = new MsgAudioModel();
        AttachModel attachModel = new AttachModel();
        attachModel.setFileLocalPath(file2.getAbsolutePath());
        audioModel.setSecond(timeTrad);
        audioModel.setAttachmentModel(attachModel);
        sendMsgByContentModel(audioModel);
    }

    /***
     * 修改发送消息的状态
     *
     * @param msgNo       消息编号
     * @param status_code 发送状态
     */
    private void updateMsgStatus(String msgNo, int status_code) {
        String send_status = "";
        if (status_code == MsgStatusType.SEND_MSG_SUCCESS) {
            send_status = "y";
        } else {
            send_status = "n";
        }

        chatAdapter.updateListViewSendStatus(msgNo, send_status);

        if (status_code == MsgStatusType.NON_FRIEND) {
            IMApplication.showToast(getResources().getString(R.string.chat_tip_no_friend));
        } else if (status_code == MsgStatusType.NO_IN_CHAT) {
            IMApplication.showToast(getResources().getString(R.string.chat_tip_not_in_group));
        }
    }

    /**
     * 获取当前会话对象数据(个人信息或者群数据)
     */
    private void getChatInfo() {
        if (sessionModel.getSessionType() == PacketType.PERSONAL) {
            if (sessionModel.getSessionId() == Long.valueOf(IMApplication.getCustId())) {
                to_name = IMApplication.config.getUserName();
            } else {
                FriendEntity entity = FriendDB.getFriend(sessionModel.getSessionId() + "");
                String name = IMApplication.config.getFriendsRemarkName(sessionModel.getSessionId() + "");
                if (TextUtils.isEmpty(name)) {
                    if (entity != null && !TextUtils.isEmpty(entity.cust_id) && !TextUtils.isEmpty(entity.nick_name)) {
                        name = entity.remarks_name;
                        if (TextUtils.isEmpty(name)) {
                            to_name = entity.nick_name;
                        } else {
                            to_name = name;
                        }
                    }
                } else {
                    to_name = name;
                }
            }
            from_cust_name = IMApplication.config.getUserName();
        } else if (sessionModel.getSessionType() == PacketType.GROUP) {
            GroupTalkEntity groupTalk = groupTalkDbManager.queryGroupByGroupId(sessionModel.getSessionId());
            GroupMemberEntity mGroupMemberEntity = mGroupMemberManager.getSingleParticipant(sessionModel.getSessionId() + "",
                    IMApplication.getCustId());
            if (mGroupMemberEntity != null && !TextUtils.isEmpty(mGroupMemberEntity.nick_name)) {
                from_cust_name = mGroupMemberEntity.nick_name;
            } else {
                from_cust_name = IMApplication.config.getUserName();
            }
            if (groupTalk != null) {
                is_show_group_member_name = groupTalk.is_show_member_name;
                is_group_admin = groupTalk.is_admin;
                to_name = groupTalk.group_name;
                has_count = groupTalk.has_count;
                if (TextUtils.isEmpty(to_name)) {
                    to_name = MessageFormat.format(getResources().getString(R.string.group_talk_memeber), groupTalk.has_count);
                }
                if (is_group_admin == 1 && groupTalk.request_count > 0) {
                    hasNewFriendButton.setVisibility(View.VISIBLE);
                }
                /** org_type_id == 3表示经费群 **/
                if (groupTalk.org_type_id == 3) {
                    getGroupFundsAmount();
                }
            }
        }
    }

    /**
     * 广播接收器
     *
     * @author SL
     */
    private class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BroadcastAction.ACTION_MSG_RECIVE)) {
                /** 接受消息 **/
                Bundle bundle = intent.getExtras();
                // QyxMsg message = bundle.getParcelable("message");
                ArrayList<QyxMsg> arrayList = bundle.getParcelableArrayList("message");
                Message m = myHandler.obtainMessage();
                m.obj = arrayList;
                m.what = 3;
                myHandler.sendMessage(m);
            } else if (action.equals(BroadcastAction.ACTION_MSG_SEND_STAUTS)) {
                /** 发送消息状态 **/
                String msg_no = intent.getStringExtra("msg_no");
                int status_code = intent.getIntExtra("status_code", 0);
                if (status_code == 0) {
                    IMApplication.showToast(getResources().getString(R.string.no_network));
                }
                SendStatusCls mSendStatus = new SendStatusCls();
                mSendStatus.msg_no = msg_no;
                mSendStatus.status_code = status_code;
                Message m = myHandler.obtainMessage();
                m.obj = mSendStatus;
                m.what = 5;
                myHandler.sendMessage(m);
            } else if (action.equals(BroadcastAction.CLEAR_MSG_ACTION)) {
                /** 清空消息记录 **/
                Message msg = myHandler.obtainMessage();
                msg.what = 7;
                myHandler.sendMessage(msg);
            } else if (action.equals(BroadcastAction.UPDATE_DOWNLAOD_FILE_STAUS)) {
                /** 文件下载状态 **/
                Bundle bundle = intent.getExtras();
                QyxMsg message = (QyxMsg) bundle.get("msg");
                Message m = myHandler.obtainMessage();
                m.what = 11;
                m.obj = message;
                myHandler.sendMessage(m);
            } else if (action.equals(BroadcastAction.ACTION_REFUSE_VIDEO_CHAT)) {
                /** 收到拒绝视频通话 **/
                String msg_no = intent.getStringExtra("msg_no");
                if (chatAdapter != null) {
                    chatAdapter.updateListViewVideChatResultType(msg_no, VideoChatResultType.VideoChatResultTypeRefuse);
                }
            } else if (action.equals(BroadcastAction.ACTION_CANCEL_CALL_VIDEO_CHAT)) {
                /** 对方取消视频通话 **/
                String msg_no = intent.getStringExtra("msg_no");
                if (chatAdapter != null) {
                    chatAdapter.updateListViewVideChatResultType(msg_no, VideoChatResultType.VideoChatResultTypeCancelCall);
                }
            } else if (action.equals(BroadcastAction.ACTION_WITHDRAW_MSG)) {
                String msg_no = intent.getStringExtra("msg_no");
                if (chatAdapter != null) {
                    chatAdapter.otherWithdrawMsg(msg_no);
                }
            } else if (action.equals(BroadcastAction.ACTION_MESSAGE_AT)) {
                String cust_name = intent.getStringExtra("cust_name");
                /** 输入框显示要@的用户名称 **/
                String result = "";
                if (sessionModel.getSessionType() == PacketType.GROUP) {
                    result = sendEdit.getText().toString() + "@" + cust_name + " ";
                } else {
                    result = sendEdit.getText().toString() + cust_name + " ";
                }
                sendEdit.setText(result);
                sendEdit.setSelection(sendEdit.getText().toString().length());
                sendEdit.requestFocus();
            } else if (action.equals(BroadcastAction.ACTION_REFRESH_STICKER)) {
                /** 刷新表情 **/
                final CheckEmojiEntity mCheckEmojiEntity = facePanelManager.getCheckEmojiEntity();
                initFacePanelView();
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        facePanelManager.setCheckEmojiEntity(mCheckEmojiEntity);
                    }
                }, 100);

            } else if (action.equals(BroadcastAction.DELETE_FRIEND_ACTION)) {
                String cust_id = intent.getStringExtra("cust_id");
                if (sessionModel != null && !TextUtils.isEmpty(cust_id) && cust_id.equals(sessionModel.getSessionId() + "")
                        && sessionModel.getSessionType() == PacketType.PERSONAL) {
                    finish();
                }
            }
        }
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 3) {
                ArrayList<QyxMsg> arrayList = (ArrayList<QyxMsg>) msg.obj;
                int count = chatAdapter.getCount();
                boolean is_show_msg = false;
                if (count > 0) {
                    QyxMsg messageLast = chatAdapter._msgList.get(count - 1).msg;
                    if (messageLast._id == arrayList.get(arrayList.size() - 1)._id) {
                        is_show_msg = true;
                    }
                }
                if (!is_show_msg) {
                    boolean HAS_APPLY_JOIN_GROUP_TALK = false;
                    for (int i = 0, size = arrayList.size(); i < size; i++) {
                        QyxMsgView mQyxMsgView = new QyxMsgView();
                        mQyxMsgView.msg = arrayList.get(i);
                        chatAdapter.addMessage(mQyxMsgView);
                        if (arrayList.get(i).msg_content_type == MsgContentType.APPLY_JOIN_GROUP_TALK) {
                            HAS_APPLY_JOIN_GROUP_TALK = true;
                        }
                    }
                    if (HAS_APPLY_JOIN_GROUP_TALK) {
                        if (is_group_admin == 1) {
                            hasNewFriendButton.setVisibility(View.VISIBLE);
                        }
                    } else if (is_get_history) {
                        try {
                            int unread_count = 0;
                            if (!TextUtils.isEmpty(unread_msg.getText().toString())) {

                                if (unread_msg.getText().equals("99")) {
                                    if (unread_msg.getTag() != null) {
                                        unread_count = (Integer) unread_msg.getTag();
                                    }
                                    unread_count += arrayList.size();
                                    unread_msg.setTag(unread_count);
                                    unread_msg.setVisibility(View.VISIBLE);
                                    return false;
                                }
                                unread_count = Integer.valueOf(unread_msg.getText().toString());
                                unread_count += arrayList.size();
                            } else {
                                unread_count += arrayList.size();
                            }
                            unread_msg.setTag(unread_count);
                            if (unread_count < 99) {
                                unread_msg.setText(unread_count + "");
                            } else {
                                unread_msg.setText("99");
                            }
                            unread_msg.setVisibility(View.VISIBLE);
                        } catch (Exception e) {
                            unread_msg.setVisibility(View.GONE);
                            unread_msg.setText("");
                        }
                        return false;
                    }
                    scrollToEnd();
                }
            } else if (msg.what == 5) {
                SendStatusCls mSendStatusCls = (SendStatusCls) msg.obj;
                updateMsgStatus(mSendStatusCls.msg_no, mSendStatusCls.status_code);
            } else if (msg.what == 7) {
                qyxMsgsArrayList.clear();
                getDBmsgAndRefresh();
                chatAdapter = new ChatAdapter(ChatActivity.this, qyxMsgsArrayList, sendEdit, is_show_group_member_name);
                listView.setAdapter(chatAdapter);
                if (qyxMsgsArrayList.size() > 0) {
                    scrollToEnd();
                }
            } else if (msg.what == 10) {
                chatAdapter.updateListViewSendStatus(msg.obj.toString(), "");
            } else if (msg.what == 11) {
                if (chatAdapter != null) {
                    QyxMsg message = (QyxMsg) msg.obj;
                    for (int i = 0, len = chatAdapter._msgList.size(); i < len; i++) {
                        if (chatAdapter._msgList.get(i).msg.msg_no.equals(message.msg_no)) {
                            chatAdapter._msgList.get(i).msg.baseContentModel.getAttachmentModel().setFileLocalPath(
                                    message.baseContentModel.getAttachmentModel().getFileLocalPath());
                            break;
                        }
                    }
                    chatAdapter.notifyDataSetChanged();
                }
            }

            return false;
        }
    });

    /**
     * 发送消息将消息列表滚动到底部
     */
    private void scrollToEnd() {
        is_get_history = false;
        unread_msg.setText("");
        unread_msg.setVisibility(View.GONE);
        final int len = chatAdapter.getCount();
        if (len <= 0) {
            return;
        }

        listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                listView.setSelection(len);
            }
        }, 300);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        if (facePanelManager != null) {
            if (facePanelManager.getPanelStatus() == 0) {
                finish();
            } else {
                hideFacePanel.hideFacePanel();
            }
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        if (chatAdapter != null) {
            chatAdapter.stopPlayRecord();
        }
        if (msgReceiver != null) {
            unregisterReceiver(msgReceiver);
        }
        rotate.cancel();
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        initData();
    }

    /**
     * 发送好友名片对话框
     *
     * @param friendEntity
     */
    private void showSendCradDailog(final FriendEntity friendEntity) {
        DialogUtility.showDialog(ChatActivity.this,
                MessageFormat.format(getResources().getString(R.string.send_user_crad), friendEntity.nick_name), R.string.sure,
                R.string.cancel, true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        MsgCradModel cradModel = new MsgCradModel();
                        cradModel.setCustId(friendEntity.cust_id);
                        cradModel.setCustName(friendEntity.nick_name);
                        cradModel.setCradType(BusinessCradType.PERSONAL_CRAD);
                        sendMsgByContentModel(cradModel);
                    }
                });
    }

    /**
     * 发送视频通话请求
     */
    private void sendVideoChat() {
        String uuidStr = UUID.randomUUID().toString();
        if (!TextUtils.isEmpty(uuidStr)) {
            uuidStr = uuidStr.replace("-", "");
            MsgRequestVideoChatModel msgRequestVideoChatModel = new MsgRequestVideoChatModel();
            msgRequestVideoChatModel.setContent(uuidStr);
            sendMsgByContentModel(msgRequestVideoChatModel);
        }
    }

    /**
     * 获取公众号菜单
     *
     * @param custid
     */
    private void getMenu(long custid) {
        mPublicNumHandle.getPublicNumMenu(custid + "", new PublicNumHandle.IGetPublicNumMenu() {

            @Override
            public void getPublicNumMenuResult(int status, String msg, ArrayList<PublicNumMenu> arrayList) {
                if (status == 0 && arrayList != null && arrayList.size() > 0) {
                    facePanelManager.setPublicNumData(arrayList);
                } else {
                    // TODO 隐藏软键盘
                    facePanelManager.hidePublicNumView();
                }
            }
        });

    }

    /**
     * 添加验证消息
     *
     * @param msg
     */
    private void addVerifMsg(QyxMsg msg) {
        QyxMsg msg2 = new QyxMsg();
        msg2.from_cust_id = msg.from_cust_id;
        msg2.to_cust_id = msg.to_cust_id;
        msg2.to_cust_name = msg.to_cust_name;
        msg2.from_cust_id = msg.from_cust_id;
        msg2.from_cust_name = msg.from_cust_name;
        /** 非好友验证消息 **/
        msg2.msg_content_type = MsgOtherType.msgVerifMsg;
        msg2.content = MessageFormat.format(getResources().getString(R.string.verif_msg_content), msg2.to_cust_name);
        msg2.msg_no = msg2.getMsgNo(msg2.from_cust_id + "", msg2.to_cust_id + "", "0");
        msgManager.insertMsg(msg2);
        QyxMsgView message = new QyxMsgView();
        message.msg = msg2;
        chatAdapter.addMessage(message);
    }
}